package com.wzz.demo.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.wzz.demo.dao.PermissionDao;
import com.wzz.demo.dao.UserDao;
import com.wzz.demo.entity.MyUser;
import com.wzz.demo.entity.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<MyUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        MyUser myUser = userDao.selectOne(queryWrapper);


        if(myUser!=null){
            List<Permission> permissions = permissionDao.findByUserid(myUser.getUserid());
            Collection<? extends GrantedAuthority> authorities=permissions.stream().map(item->new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
            return new User(username,myUser.getUserpwd(),authorities);
        }
        return null;
    }
}
